<template>
  <div class="tagManage">
    <el-tabs v-if="userInfo.characterId=='1'" v-model="activeGroup" type="card" @tab-click="handleTabClick">
      <el-tab-pane v-for="group,index in groupMenu" :label="group.groupName" :name="group.groupId.toString()" :key="index.toString()"></el-tab-pane>
    </el-tabs>
    <el-form>
      <el-form-item>
        <el-col :span="8">
          <el-input placeholder="标签名称" v-model="searchForm.wd"></el-input>
        </el-col>
        <el-col :span="3"><el-button type="primary" style="margin-left:10px" @click="submitSearch">搜索</el-button></el-col>
      </el-form-item>
      <el-form-item label="标签分类">
        <el-col :span="22">
          <tag-select ref="tagSelect" :tagClass="tagClass" v-on:change="handleSelect"></tag-select>
        </el-col>
      </el-form-item>
    </el-form>
    <div class="operatArea">
      <el-button @click="handleAddTag">新建标签</el-button>
      <el-button @click="handelDelMore(selections)" :disabled="!selections.length">批量删除标签</el-button>
      <el-dropdown style="margin-left:10px" @command="handleMoveClick">
        <el-button>
          批量移动标签<i class="el-icon-caret-bottom el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown" style="min-width:130px;">
          <el-dropdown-item command="conditions">移动筛选结果</el-dropdown-item>
          <el-dropdown-item command="selections" :disabled="!selections.length">移动勾选选项</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button v-if="!showTree" type="text" @click="showTree = true">管理标签分类</el-button>
      <el-button v-else type="text" @click="showTree = false">隐藏标签分类</el-button>
    </div>
    <!-- 标签树 -->
    <tag-Tree 
      v-show="showTree"
      :groupId="activeGroup"
      :class="{show: showTree}"
      :edit="treeEdit"
      @node-click="handleTreeClick"
      @add-success="getChildTagClass({gid: activeGroup})">
    </tag-Tree>
    <div class="table-wrap">
      <el-table v-loading="tbLoading" element-loading-text="拼命加载中" :data="tagList.list" @selection-change="handleSelectionChange" stripe class="table">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column prop="name" label="标签名" className="is-center">
        </el-table-column>
        <el-table-column prop="pname" label="标签分类" className="is-center">
        </el-table-column>
        <el-table-column label="标签成员" width="200px" className="is-center">
          <template slot-scope="scope">
            {{scope.row.userNum + (scope.row.userNumBuyer || 0)}}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" className="is-center">
          <template slot-scope="scope">
            {{dateFormat(scope.row.createTime)}}
          </template>
        </el-table-column>
        <el-table-column label="操作" className="is-center">
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="newName = curName = scope.row.name;curId = scope.row.id;dialogVisible2=true">编辑</el-button>
            <el-button v-if="!scope.row.top" size="small" type="text" @click="handleSetTop(scope.row.id, true)">置顶</el-button>
            <el-button v-else size="small" type="text" @click="handleSetTop(scope.row.id, false)">取消置顶</el-button>
            <el-button size="small" type="text" class="red" @click="handleDel(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          :current-page.sync="searchForm.page"
          :page-size.sync="searchForm.size"
          layout="sizes, total, prev, pager, next, jumper"
          :total="tagList.page.total"
          :page-sizes="[10, 30, 50, 100]"
          @current-change="submitSearch()"
          @size-change="handleSizeChange">
        </el-pagination>
      </div>
    </div>
    <transition name="router-fade" mode="out-in">
      <div v-if="isMoveTags" class="mask" @click="isMoveTags=false"></div>
    </transition>
    <!-- 新建标签弹出层 -->
    <el-dialog title="新建标签" :visible.sync="dialogVisible" custom-class="dialog-addTag">
      <el-form label-width="40px">
        <el-form-item label="分类">
          <tag-select ref="tagSelect2" :tagClass="tagClass" v-on:change="handleSelect"></tag-select>
        </el-form-item>
        <el-form-item label-width="0">
          <el-input v-model="newTags" type="textarea" :rows="3" placeholder="请输入标签..."></el-input>
        </el-form-item>
        <p class="tips">如果是同时新建多个标签，用回车或者“,”隔开。</p>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveTag" :loading="isSave">保存</el-button>
      </div>
    </el-dialog>
    <!-- 编辑标签弹出层 -->
    <el-dialog title="编辑标签" :visible.sync="dialogVisible2" custom-class="dialog-addTag" width="30%">
      <el-input v-model="newName" placeholder="新标签名"></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="handleEditTag" :loading="isSave">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {mapState, mapActions} from 'vuex'
  import tagTree from '@/components/common/cusManage/tagTree'
  import tagSelect from '@/components/common/cusManage/tagSelect'
  export default {
    data () {
      return {
        searchForm: {
          wd: '',
          page: 1,
          size: 10
        },
        activeGroup: '-1',
        newTags: '',
        isMoveTags: false,
        newName: '',
        dialogVisible: false,
        dialogVisible2: false,
        treeEdit: true,
        showTree: false,
        tbLoading: true,
        isSave: false,
        selections: []
      }
    },
    activated () {
      this.getGroupMenu()
        .then(() => {
          this.activeGroup = this.groupMenu[0].groupId + ''
          this.getPageData(this.activeGroup)
        })
    },
    components: {tagTree, tagSelect},
    watch: {
      isMoveTags (val) {
        this.treeEdit = !val
      }
    },
    computed: {
      ...mapState({
        tagList: state => state.cusManage.tagList,
        groupMenu: state => state.groupMenu,
        tagClass: state => state.cusManage.tagClass,
        userInfo: state => state.userInfo
      })
    },
    methods: {
      ...mapActions(['getGroupMenu', 'searchTags', 'getTagTree', 'addTagClass', 'getChildTagClass', 'addTag', 'delTag', 'editTag', 'setTopTag', 'deleteTagsMore', 'moveTags']),
      // 日期格式化
      dateFormat (date) {
        return this.$date.format(new Date(date), 'YYYY-MM-DD hh:mm:ss')
      },
      // 初始化页面数据
      getPageData (gid) {
        this.searchTags({...this.searchForm, gid})
          .then(res => {
            if (res.data.code === 1) {
              this.tbLoading = false
            }
          })
        this.getChildTagClass({gid: gid})
      },
      // 切换标签
      handleTabClick (pane) {
        this.$refs['tagSelect'].models = []
        this.getPageData(pane.name)
      },
      // 选择标签分类
      handleSelect (pid, index) {
        if (pid) {
          this.getChildTagClass({index: index, pid: pid, gid: this.activeGroup})
        }
      },
      // 添加标签
      handleAddTag () {
        this.dialogVisible = true
        this.$nextTick(function () {
          this.$refs['tagSelect2'].models = this.$refs['tagSelect'].models
        })
      },
      // 保存新建标签
      handleSaveTag () {
        let tagName = this.newTags.split(/[\n,]/).join(',')
        let gid = this.activeGroup
        let pid = this.$refs['tagSelect2'].models.filter(item => item) // 获取选择的标签分类id
        this.isSave = true
        this.addTag({tagName, gid, pid: pid[pid.length - 1]})
          .then((res) => {
            this.isSave = false
            this.dialogVisible = false
            if (res.data.code === 1) {
              this.submitSearch()
              this.$message({
                type: 'success',
                message: '添加成功'
              })
            }
          })
      },
      async handleEditTag () {
        if (this.newName !== this.curName) {
          const res = await this.editTag({tagId: this.curId, newName: this.newName})
          if (res.data.code === 1) {
            this.dialogVisible2 = false
            this.submitSearch()
            this.$message({
              type: 'success',
              message: '修改成功'
            })
          }
        }
      },
      // 删除标签
      handleDel (id) {
        this.$confirm('是否确认删除标签？', '确认删除')
          .then(() => {
            return this.delTag({tagId: id, gid: this.activeGroup})
          })
          .then(res => {
            if (res.data.code === 1) {
              this.submitSearch()
              this.$message({
                type: 'success',
                message: '删除成功'
              })
            }
          })
      },
      handleSelectionChange (selections) {
        // this.selections = selections
        this.selections = selections.map(item => item.id)
      },
      // 批量删除标签
      handelDelMore (selections) {
        this.$confirm('是否确认删除' + selections.length + '个标签？', '确认删除')
        .then(() => {
          this.deleteTagsMore(selections).then(res => {
            if (res.data.code === 1) {
              this.submitSearch()
              this.$message({
                type: 'success',
                message: '删除成功'
              })
            }
          })
        })
      },
      // 置顶标签
      handleSetTop (tagId, ifTop) {
        this.setTopTag({tagId, ifTop})
          .then(() => {
            this.getPageData(this.activeGroup)
          })
      },
      // 改变分页大小
      handleSizeChange (size) {
        this.searchForm.size = size
        this.submitSearch()
      },
      // 管理标签分类
      handleManageClass () {
        this.showTree = !this.showTree
      },
      // 搜索
      submitSearch () {
        let pid = this.$refs['tagSelect'].models.filter(item => item) // 获取选择的标签分类id
        this.searchTags({...this.searchForm, gid: this.activeGroup, pid: pid[pid.length - 1]})
      },
      // 点击批量移动标签
      async handleMoveClick (type) {
        this.isMoveTags = true
        this.showTree = true
        this.moveStatus = type
      },
      // 选择移动标签分类
      async handleTreeClick (node) {
        if (this.isMoveTags) {
          if (node.child.length) {
            this.$message.warning('只能移动到最深层的分类')
            return false
          }
          if (this.moveStatus === 'selections') {
            const res = await this.moveTags({
              tagIds: this.selections,
              groupId: node.id
            })
            if (res.data.code === 1) {
              this.$message.success('移动成功')
              this.isMoveTags = false
              this.submitSearch()
            }
          } else {
            let pid = this.$refs['tagSelect'].models.filter(item => item) // 获取选择的标签分类id
            const res = await this.moveTags({
              condition: {...this.searchForm, gid: this.activeGroup, pid: pid[pid.length - 1]},
              groupId: node.id
            })
            if (res.data.code === 1) {
              this.$message.success('移动成功')
              this.isMoveTags = false
              this.submitSearch()
            }
          }
        }
      }
    }
  }
</script>
<style lang="scss">
  .tagManage{
    .operatArea{margin-bottom:20px}
    .el-select{margin-left:10px}
    .tagTree{
      &{position:relative;float:left;min-width:200px;z-index:2000}
      .del{margin-left:5px;}
      .el-tree-node__expand-icon{margin:-2px 0 0;font-size: 16px;}
    }
    .tagTree.show ~ .table-wrap{margin-left:210px;width:calc(100% - 220px) !important}
    .dialog-addTag .tips{margin-top:-15px;}
    .mask{position:fixed;top:0;right:0;bottom:0;left:0;background:rgba(0,0,0,.5);z-index:100}
    .el-tree-node__content{line-height: 26px;}
  }
</style>
